package com.atguigu.tingshu.payment.service.impl;

import com.atguigu.tingshu.account.AccountFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.model.payment.PaymentInfo;
import com.atguigu.tingshu.order.client.OrderFeignClient;
import com.atguigu.tingshu.payment.mapper.PaymentInfoMapper;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wechat.pay.java.service.payments.model.Transaction;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@SuppressWarnings({"all"})
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {

    @Autowired
    private OrderFeignClient orderFeignClient;

    @Autowired
    private AccountFeignClient accountFeignClient;

    /**
     * 保存本地交易记录
     *
     * @param paymentType:支付类型 1301-订单 1302-充值
     * @param orderNo:         订单编号
     * @return 本地交易对接微信支付
     */
    @Override
    public PaymentInfo savePaymentInfo(String paymentType, String orderNo) {
        //1.根据订单编号查询本地校验记录，如果存在，则返回存在记录即可
        PaymentInfo paymentInfo = baseMapper.selectOne(
                new LambdaQueryWrapper<PaymentInfo>()
                        .eq(PaymentInfo::getOrderNo, orderNo)
        );
        if (paymentInfo != null) {
            return paymentInfo;
        }
        //2.如果不存在，则构建本地交易记录对象
        paymentInfo = new PaymentInfo();
        //2.1 交易状态：1401-未支付 1402-已支付
        paymentInfo.setPaymentStatus(SystemConstant.PAYMENT_STATUS_UNPAID);
        //2.2 交易编号（微信或支付）
        paymentInfo.setPayWay(SystemConstant.ORDER_PAY_WAY_WEIXIN);
        //2.3 支付类型：1301-订单 1302-充值
        paymentInfo.setPaymentType(paymentType);
        //2.4 订单编号
        paymentInfo.setOrderNo(orderNo);
        //处理支付类型为 订单
        if (SystemConstant.PAYMENT_TYPE_ORDER.equals(paymentType)) {
            //远程调用订单服务获取订单信息，封装用户ID，交易金额，交易内容
            OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderNo).getData();
            String orderStatus = orderInfo.getOrderStatus();
            if (!SystemConstant.ORDER_STATUS_UNPAID.equals(orderStatus)) {
                throw new RuntimeException("订单状态有误！");
            }
            //2.5 用户ID
            paymentInfo.setUserId(orderInfo.getUserId());
            //2.6 交易金额
            paymentInfo.setAmount(orderInfo.getOrderAmount());
            //2.7 交易内容
            paymentInfo.setContent(orderInfo.getOrderTitle());
        }
        //处理支付类型为充值
        if (SystemConstant.PAYMENT_TYPE_RECHARGE.equals(paymentType)) {
            //远程调用账户服务获取充值信息，封装用户ID，交易金额，交易内容
            RechargeInfo rechargeInfo = accountFeignClient.getRechargeInfo(orderNo).getData();
            String rechargeStatus = rechargeInfo.getRechargeStatus();
            if (!SystemConstant.ORDER_STATUS_UNPAID.equals(rechargeStatus)) {
                throw new RuntimeException("充值状态有误！");
            }
            //2.5 用户ID
            paymentInfo.setUserId(rechargeInfo.getUserId());
            //2.6 交易金额
            paymentInfo.setAmount(rechargeInfo.getRechargeAmount());
            //2.7 交易内容
            paymentInfo.setContent("充值：" + rechargeInfo.getRechargeAmount());
        }
        //2.7 以下3项信息： 第三方支付平台支付订单编号,等用户支付成功后，异步回调业务处理再更新
        //paymentInfo.setOutTradeNo();
        //paymentInfo.setCallbackTime();
        //paymentInfo.setCallbackContent();
        baseMapper.insert(paymentInfo);
        return paymentInfo;
    }

    /**
     * 用户支付成功后，更新交易记录
     *
     * @param transaction 微信交易对象
     */
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public void updatePaymentInfo(Transaction transaction) {
        //1.根据商户订单编号查询本地交易记录
        String orderNo = transaction.getOutTradeNo();
        PaymentInfo paymentInfo = baseMapper.selectOne(
                new LambdaQueryWrapper<PaymentInfo>()
                        .eq(PaymentInfo::getOrderNo, orderNo)
        );
        String paymentStatus = paymentInfo.getPaymentStatus();
        if (SystemConstant.PAYMENT_STATUS_PAID.equals(paymentStatus)) {
            throw new RuntimeException("该订单已支付！");
        }
        paymentInfo.setPaymentStatus(SystemConstant.PAYMENT_STATUS_PAID);
        paymentInfo.setOutTradeNo(transaction.getTransactionId());
        paymentInfo.setCallbackTime(new Date());
        paymentInfo.setCallbackContent(transaction.toString());
        baseMapper.updateById(paymentInfo);

        //支付类型：1301-订单 1302-充值
        String paymentType = paymentInfo.getPaymentType();
        //2. 处理支付类型为 订单
        if (SystemConstant.PAYMENT_TYPE_ORDER.equals(paymentType)) {
            Result result = orderFeignClient.orderPaySuccess(orderNo);
            if (result.getCode().intValue() != 200) {
                throw new GuiguException(result.getCode(), result.getMessage());
            }
        }

        //3. 处理支付类型为 充值
        if (SystemConstant.PAYMENT_TYPE_RECHARGE.equals(paymentType)) {
            //3.1 远程调用账户服务，完成充值业务
            Result result = accountFeignClient.rechargePaySuccess(orderNo);
            //3.2 判断业务状态码是否为200
            if (result.getCode().intValue() != 200) {
                throw new GuiguException(result.getCode(), result.getMessage());
            }
        }

    }
}
